package com.axter.libs.photo.utils;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;

/**
 * Created by zhaobo on 2016/9/29.
 */
public class OpenCameraActivity extends Activity {
    private static final int RESULT_CAMERA = 101;
    // 保存值key 拍照照片地址
    public static final String CAMERA_PATH = "cameraPath";
    private static final String CAMERA_OPEN = "isOpenCamera";

    private String cameraPath;
    /** 是否启动了照相机 */
    private boolean isOpenCamera = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getIntent() != null && getIntent().getExtras() != null && getIntent().getExtras().containsKey(CAMERA_PATH)) {
            cameraPath = getIntent().getExtras().getString(CAMERA_PATH);
        }
        if (TextUtils.isEmpty(cameraPath)) {
            cameraPath = BaseUtils.getFilePath(getApplicationContext(), null, System.currentTimeMillis() + ".jpg");
        }
        onRestoreInstanceState(savedInstanceState);
        if (!isOpenCamera) {
            isOpenCamera = true;
            if (!BaseUtils.openCamera(this, cameraPath, RESULT_CAMERA)) {
                finish();
            }
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        if (outState == null) {
            return;
        }
        outState.putString(CAMERA_PATH, cameraPath);
        outState.putBoolean(CAMERA_OPEN, isOpenCamera);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        if (savedInstanceState == null) {
            return;
        }
        if (savedInstanceState.containsKey(CAMERA_PATH)) {
            cameraPath = savedInstanceState.getString(CAMERA_PATH);
        }
        if (savedInstanceState.containsKey(CAMERA_OPEN)) {
            isOpenCamera = savedInstanceState.getBoolean(CAMERA_OPEN);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK && requestCode == RESULT_CAMERA) {
            if (data == null) {
                data = new Intent();
            }
            data.putExtra(CAMERA_PATH, cameraPath);
            setResult(Activity.RESULT_OK, data);
        }
        finish();
    }
}
